package com.example.myone.Util;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Base64;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.example.myone.Entity.User;
import com.example.myone.R;

import java.io.ByteArrayOutputStream;

public class ImageUtils {
    // 使用base64编码为图片设置背景
    public static void setImageByBase64Str(Context context, ImageView image, String base64) {
        Glide.with(context)
                .asBitmap()
                .load(ImageUtils.decodeBase64ToBitmap(base64))
                .apply(new RequestOptions().placeholder(R.drawable.placeholder))
                .into(image);
    }
    private static final int maxSizeInBytes = 409600;
    private static final int DEFAULT_QUALITY = 100; // 默认初始质量
    private static final int QUALITY_STEP = 20; // 降低质量的步长

    // 读取资源图片转换为base64编码
    public static String convertImageToBase64(Context context, int resourceId) {
        // 从资源ID加载图像文件
        Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), resourceId);
        return compressAndEncodeToBase64(bitmap);
    }
    // 读取bitmap图片转换为base64编码
    public static String convertBitmapToBase64(Bitmap bitmap) {
        return compressAndEncodeToBase64(bitmap);
    }
    // 将bitmap图片转换为base64编码的字符串
    private static String compressAndEncodeToBase64(Bitmap bitmap) {
        // 压缩图像直到大小小于指定的最大大小
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        int quality = DEFAULT_QUALITY; // 初始质量为默认值
        bitmap.compress(Bitmap.CompressFormat.JPEG, quality, byteArrayOutputStream);
        while (byteArrayOutputStream.size() > maxSizeInBytes && quality > 0) {
            byteArrayOutputStream.reset(); // 重置输出流以便重新压缩
            quality -= QUALITY_STEP; // 降低质量
            bitmap.compress(Bitmap.CompressFormat.JPEG, quality, byteArrayOutputStream);
        }
        // 将Bitmap对象转换为Base64字符串
        byte[] byteArray = byteArrayOutputStream.toByteArray();
        return Base64.encodeToString(byteArray, Base64.DEFAULT);
    }
    // 将Base64编码的图片转换成Bitmap类型的数据
    public static Bitmap decodeBase64ToBitmap(String base64Str) {
        byte[] decodedBytes = Base64.decode(base64Str, Base64.DEFAULT);
        return BitmapFactory.decodeByteArray(decodedBytes, 0, decodedBytes.length);
    }
}